import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { DownloadOutlined } from "@ant-design/icons";
import type { TableColumnsType, TableProps } from "antd";
import { Button, Flex, Tag, Tooltip } from "antd";
import SearchForm from "@/components/search-form";
import Table from "@/components/table";
import CardButton from "./components/card-button";
import EditButton from "./components/edit-button";
import LogoutButton from "./components/logout-button";
import { useUserList } from "@/api";
import { USER_STATUS_OPTIONS } from "@/constants/options";
import { useExcelExport } from "@/hooks";
import { useUserManagerStore } from "@/stores/modules/userManager";
import { dateFormat } from "@/utils/date";

import { UserDataType } from "@/types/user";

type TableRowSelection<T extends object = object> = TableProps<T>["rowSelection"];

export default function UserManagement() {
  const columns: TableColumnsType<UserDataType> = [
    {
      title: "用户ID",
      dataIndex: "id",
      key: "id",
      width: 100,
    },
    {
      title: "用户昵称",
      dataIndex: "nickname",
      key: "nickname",
      width: 150,
      ellipsis: true,
      render: (_, record) => <Tooltip title={record.nickname}>{record.nickname}</Tooltip>,
    },
    {
      title: "手机号",
      dataIndex: "mobile",
      key: "mobile",
      width: 150,
    },
    {
      title: "小红书账号",
      dataIndex: "homepage",
      key: "homepage",
      width: 150,
      // render: (_, record) => <Link to={`/user/account/${record.id}`}>{record.avatar}</Link>,
      render: (_, record) => (
        <Button type="link" size="small" onClick={() => handleViewDetail(record)}>
          -
        </Button>
      ),
    },
    {
      title: "名片数量",
      dataIndex: "company",
      key: "company",
      width: 80,
      render: (_, record) => <CardButton userId={record.id}>{record.businessCardCount}</CardButton>,
      // render: () => "-",
    },
    {
      title: "待审核",
      dataIndex: "waitingReview",
      key: "waitingReview",
      width: 80,
      render: (_, record) => (
        <Button type="link" size="small" onClick={() => handleViewDetail(record)}>
          {record.userAccountPendingCount}
        </Button>
      ),
    },
    {
      title: "注册时间",
      dataIndex: "createdAt",
      key: "createdAt",
      width: 150,
      render: (_, record) => dateFormat(record.createdAt, "YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "最后登录",
      dataIndex: "lastLoginAt",
      key: "lastLoginAt",
      width: 150,
      render: (_, record) => dateFormat(record.lastLoginAt, "YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "登录地址",
      dataIndex: "lastLoginIp",
      key: "lastLoginIp",
      width: 150,
      render: () => "-",
    },
    {
      title: "帐号状态",
      dataIndex: "status",
      key: "status",
      width: 80,
      render: (_, record) => (
        <Tag color={record.status === "normal" ? "green" : "red"}>
          {USER_STATUS_OPTIONS.find((option) => option.value === record.status)?.label}
        </Tag>
      ),
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      fixed: "right",
      width: 80,
      render: (_, record) => {
        return (
          <Flex justify="start" gap={8}>
            <EditButton data={record} refresh={refresh} />
            <LogoutButton data={record} />
          </Flex>
        );
      },
    },
  ];

  const canHideColumns: TableColumnsType<UserDataType> = [
    {
      title: "用户ID",
      dataIndex: "userId",
      key: "userId",
    },
    {
      title: "用户昵称",
      dataIndex: "nickname",
      key: "nickname",
    },
    {
      title: "手机号",
      dataIndex: "mobile",
      key: "mobile",
    },
    {
      title: "小红书账号",
      dataIndex: "homepage",
      key: "homepage",
    },
  ];

  const schema = [
    { name: "id", label: "用户ID", type: "input" },
    { name: "nickname", label: "用户呢称", type: "input" },
    { name: "mobile", label: "手机号", type: "input" },
    { name: "homepage", label: "小红书账号", type: "input" },
    { name: "businessCardCount", label: "名片数量", type: "input" },
    {
      name: "status",
      label: "帐号状态",
      type: "select",
      componentProps: {
        options: USER_STATUS_OPTIONS,
      },
    },
    {
      name: "createdAt",
      label: "注册时间",
      type: "rangePicker",
      componentProps: { id: { start: "startDate", end: "endDate" }, format: "YYYY-MM-DD" },
    },
  ];
  const navigate = useNavigate();
  const setCurrentUserDetail = useUserManagerStore((state) => state.setCurrentUserDetail);
  const { data, loading: isFetching, refresh, runAsync: fetchList } = useUserList();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: [5, 10, 20, 50],
  });
  const [queryParams, setQueryParams] = useState({
    pageNum: 1,
    pageSize: 10,
  });
  // Excel导出配置
  const { exportData } = useExcelExport({
    filename: "用户管理",
    columns: [
      { title: "用户ID", dataIndex: "nickName", key: "nickName" },
      { title: "用户昵称", dataIndex: "phone", key: "phone" },
      { title: "手机号", dataIndex: "email", key: "email" },
      { title: "小红书账号", dataIndex: "website", key: "website" },
      {
        title: "名片数量",
        dataIndex: "company",
        key: "company",
        render: (_: any, record: any) => record.nickName || "",
      },
      {
        title: "待审核",
        dataIndex: "waitingReview",
        key: "waitingReview",
        render: (_: any, record: any) => record.nickName || "",
      },
      {
        title: "注册时间",
        dataIndex: "createdAt",
        key: "createdAt",
        render: (_: any, record: any) => record.nickName || "",
      },
      {
        title: "最后登录",
        dataIndex: "lastLoginAt",
        key: "lastLoginAt",
        render: (_: any, record: any) => record.nickName || "",
      },
      {
        title: "登录地址",
        dataIndex: "lastLoginIp",
        key: "lastLoginIp",
        render: (_: any, record: any) => record.nickName || "",
      },
      {
        title: "帐号状态",
        dataIndex: "status",
        key: "status",
        render: (_: any, record: any) => record.nickName || "",
      },
    ],
  });

  const onSearch = (values: any) => {
    const newParams = {
      ...values,
      pageNum: 1, // 搜索时重置为第一页
      pageSize: pagination.pageSize,
    };
    setQueryParams(newParams);
    setPagination({ ...pagination, current: 1 });
    fetchList(newParams);
  };

  const onPageChange = (page: number, pageSize: number) => {
    const newParams = {
      ...queryParams,
      pageNum: page,
      pageSize: pageSize,
    };
    setQueryParams(newParams);
    setPagination({
      ...pagination,
      current: page,
      pageSize: pageSize,
    });

    // 手动触发查询
    fetchList(newParams);
  };

  const handleExport = () => {
    if (selectedRowKeys.length > 0) {
      exportData(data || [], selectedRowKeys, "id");
    } else {
      window.$message?.warning("请选择要导出的数据");
    }
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<UserDataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handleViewDetail = (user: UserDataType) => {
    // 保存当前选中的用户到 store
    setCurrentUserDetail(user);
    // 跳转到详情页
    navigate(`/user/account/${user.id}`);
  };

  useEffect(() => {
    fetchList(queryParams);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="flex flex-col h-full overflow-hidden">
      <div className="mb-4 bg-white rounded-lg p-4 dark:bg-[#1f1f1f] flex-shrink-0">
        <SearchForm schema={schema} onSearch={onSearch} />
      </div>
      <div className="bg-white rounded-lg p-4 dark:bg-[#1f1f1f] flex-1 flex flex-col overflow-hidden">
        <Table
          columns={columns}
          canHideColumns={canHideColumns}
          dataSource={data?.items}
          loading={isFetching}
          rowKey="id"
          pagination={{ ...pagination, total: Number(data?.total || 0) }}
          rowSelection={rowSelection}
          onPageChange={onPageChange}
          onRefresh={() => {
            console.log("onRefresh");
            setPagination({
              ...pagination,
              current: 1,
              pageSize: 10,
            });
            setSelectedRowKeys([]);
            refresh();
          }}
          leftActions={
            <Button size="middle" type="primary" ghost icon={<DownloadOutlined />} onClick={handleExport}>
              导出
            </Button>
          }
        />
      </div>
    </div>
  );
}
